<!-- 复制自： 运营平台
   差异： 删除商户号mchNo 的input即可。 

 -->
<template>
  <a-drawer
    :visible="vdata.visible"
    title="签名配置"
    width="40%"
    :maskClosable="false"
    @close="onClose"
  >
    <a-form ref="infoFormModel" :model="vdata.saveObject" layout="vertical" :rules="vdata.rules">
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item name="appSignType">
            <template #label>
              <span>支持的签名方式</span> &nbsp;
              <a-popover placement="top">
                <template #title><span>签名方式</span></template>
                <template #content>
                  <p>若需要使用系统测试或者{{ $SYS_NAME_MAP.MCH_APP }}APP则必须支持MD5， 若仅通过API调用则根据需求进行选择。 </p>
                </template>
                <question-circle-outlined />
              </a-popover>
            </template>

            <a-checkbox-group v-model:value="vdata.saveObject.appSignTypeObject">
              <a-checkbox value="MD5">MD5</a-checkbox>
              <a-checkbox value="RSA2">RSA2</a-checkbox>
            </a-checkbox-group>
          </a-form-item>

          <a-form-item v-show="vdata.saveObject.appSignTypeObject && vdata.saveObject.appSignTypeObject.indexOf('MD5') >= 0" label="设置MD5秘钥" name="appSecret">
            <a-textarea v-model:value="vdata.saveObject['appSecret']" :placeholder="vdata.saveObject['appSecret_ph']" type="textarea" />
            <a-button type="primary" style="margin-top: 5px;" ghost @click="randomKey(false, 128, 0)"><file-sync-outlined />随机生成私钥</a-button>
            <a-button type="primary" danger style="margin-top: 5px;margin-left: 20px;" ghost @click="showKey()"><file-search-outlined />查看完整秘钥</a-button>
          </a-form-item>

          <a-form-item v-show="vdata.saveObject.appSignTypeObject && vdata.saveObject.appSignTypeObject.indexOf('RSA2') >= 0" label="设置RSA2应用公钥" name="appRsa2PublicKey">
            <a-textarea v-model:value="vdata.saveObject['appRsa2PublicKey']" type="textarea" />
          </a-form-item>

          <a-form-item v-show="vdata.saveObject.appSignTypeObject && vdata.saveObject.appSignTypeObject.indexOf('RSA2') >= 0" label="支付网关系统公钥（回调验签使用）">
            <a-textarea :rows="6" :value="vdata.sysRSA2PublicKey" :disabled="true" type="textarea" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" @click="onClose"><close-outlined />取消</a-button>
      <a-button type="primary" :loading="vdata.btnLoading" @click="onSubmit"><check-outlined />保存</a-button>
    </div>

    <a-modal v-model:visible="vdata.isShow" title="验证密码" @ok="handleOk">
      <a-form ref="signInfo" :rules="rules" :model="vdata.viewInfo">
        <a-form-item label="支付密码" name="password">
          <a-input v-model:value="vdata.viewInfo.password" maxlength="6" type="password" autocomplete="off" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-drawer>
</template>


<script setup lang="ts">
import { API_URL_MCH_APP, req, $getSysRSA2PublicKey, $mchAppSecret } from '@/api/manage'
import {ref, reactive, getCurrentInstance} from 'vue'

const { $SYS_NAME_MAP } = getCurrentInstance()!.appContext.config.globalProperties
const props = defineProps({
  callbackFunc: { type: Function, default: () => () => ({}) }
})
  
const vdata : any =  reactive({
  isAdd: true, // 新增 or 修改
  isShow: false,
  visible: false, // 抽屉开关
  appId: '', // 应用AppId
  saveObject: {}, // 数据对象
  viewInfo: {}, // 数据对象
  btnLoading:false,
  sysRSA2PublicKey: '', 
  rules: {
    appSecret: [{
      validator:  (rule, value) => {

          // 新增 & 选择了MD5 :  必须输入MD5私钥
          if(vdata.isAdd && vdata.saveObject.appSignTypeObject.indexOf('MD5') >= 0 && !value){
            return Promise.reject('请输入MD5秘钥')
          }
          return Promise.resolve()
      }
    }],
    appRsa2PublicKey: [{
      validator:  (rule, value) => {

          // 新增 & 选择了MD5 :  必须输入MD5私钥
          if(vdata.saveObject.appSignTypeObject.indexOf('RSA2') >= 0 && !value){
            return Promise.reject('请输入RSA2应用公钥')
          }
          return Promise.resolve()
      } 
    }]
  }
})

const rules = {
  password: [{required: true, trigger: 'blur', message: '请输入支付密码' }],
}

// 表单组件
const infoFormModel = ref()
const signInfo = ref()

// 抽屉显示
const show = (appId) => {
  vdata.isAdd = !appId
  // 数据清空
  vdata.saveObject = {
    'state': 1,
    'appSecret': '',
    'defaultFlag': 1,
    'appSecret_ph': '请输入',
    appSignTypeObject: ['MD5']
  }
  
  if (infoFormModel.value !== undefined) {
    infoFormModel.value.resetFields()
  }

  if (!vdata.isAdd) { // 修改信息 延迟展示弹层
    vdata.appId = appId
    // 拉取详情
    req.getById(API_URL_MCH_APP, appId).then(res => {
      vdata.saveObject = res
      vdata.saveObject['appSecret_ph'] = res.appSecret
      vdata.saveObject['appSecret'] = ''

      vdata.saveObject.appSignTypeObject = []
      if(res.appSignType){
        vdata.saveObject.appSignTypeObject = JSON.parse(res.appSignType)
      }

    })

    vdata.visible = true
  } else {

    vdata.visible = true // 展示弹层信息
  }

  // 查询系统公钥
  $getSysRSA2PublicKey().then((res) => {
    vdata.sysRSA2PublicKey = res
  })

}
// 表单提交
const onSubmit = () => {

  // 处理签名方式
  vdata.saveObject.appSignType = JSON.stringify(vdata.saveObject.appSignTypeObject)
  
  infoFormModel.value.validate().then(() => {

    vdata.btnLoading = true
    let reqObject = Object.assign({}, vdata.saveObject) // 请求数据
  
    delete reqObject['appSecret_ph']
    if (!vdata.isAdd && reqObject['appSecret'] === '') {
        delete reqObject['appSecret']
    }

    req.addOrUpdate(vdata.isAdd ? null : vdata.appId, API_URL_MCH_APP, reqObject).then(res => {
        vdata.visible = false
        props.callbackFunc() // 刷新列表
    }).finally(() => {
        vdata.btnLoading = false
    })
  })
}


function randomKey(randomFlag, min, max) { // 生成随机128位私钥
  let str = ''
  let range = min
  const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  // 随机产生
  if (randomFlag) {
    range = Math.round(Math.random() * (max - min)) + min
  }
  for (var i = 0; i < range; i++) {
    var pos = Math.round(Math.random() * (arr.length - 1))
    str += arr[ pos ]
  }
  vdata.saveObject['appSecret'] = str
}

function showKey () {
  vdata.viewInfo.password = ''
  vdata.isShow = true
}

function handleOk() {
  signInfo.value.validate().then(valid =>{
    $mchAppSecret(vdata.viewInfo.password, vdata.appId).then((res) => {
      vdata.saveObject['appSecret'] = res
      vdata.isShow = false
    })
  })
}

const onClose = () => {
  vdata.visible = false
}

defineExpose({ show })
</script>

